import { observable, action } from 'mobx'
import axios from '../../../common/request'
import  notificationWithIcon from '../../common/notificationWithIcon';
import {Modal} from 'antd'

class ExhibitionStore {
    @observable loading=false;
    @observable halls = [{
        key:0,
        name:'',
        maxKey:0,
        areas:[{
            key:0,
            areaName: '',
            word:'',
            start:'',
            end:'',
        }]
    }]


    @observable id=''

    @observable standTotal=''

    @observable his=[]

    @observable activity=[]

    @observable current=0

    @observable list = []

    @observable imgLoading=false

    @observable imageUrl=''

    urlPre='http://'

    exhibitionInfo={}

    hasProps=false

    delHallsList=[]

    actions={
        urlPreChange:action((value)=>{
            this.urlPre=value;
        }),
        getBase64:action((img, callback) =>{
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result));
            reader.readAsDataURL(img);
        }),
        handleImgChange:action((info)=>{
            if (info.file.status === 'uploading') {
                this.imgloading=true;
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                this.actions.getBase64(info.file.originFileObj, imageUrl => {
                    this.imageUrl=imageUrl;
                    this.imgLoading=false;
                });
                //console.log(info.file.response.result.key)
                //this.props.getKey(info.file.response.result.key)
            }
        }),
        addHall:action(() => {
            let key=0
            if(this.halls.length>0) {
                key = this.halls[this.halls.length - 1].key + 1;
            }
            if(this.halls.length>19){
                notificationWithIcon('error', `最多只能创建20个展馆`)
                return;
            }
            this.halls.push({
                name:'',
                key:key,
                maxKey:0,
                areas:[{
                    key:0,
                    areaName: '',
                    word:'',
                    start:'',
                    end:'',
                }]
            })
        }),
        addRow:action((hall)=>{
            let areas=hall.areas
            let key=(++hall.maxKey);
            let areaName=''
            if(areas.length>0){
                let area=areas[areas.length-1]
                areaName=area.areaName
            }
            if(areas.length>59){
                notificationWithIcon('error', `不能创建更多展区展位`)
                return;
            }
            areas.push({
                key:key,
                areaName: areaName,
                word:'',
                start:'',
                end:'',
            });
        }),
        delHall:action((index)=>{
            if(this.halls[index].id!=undefined){
                this.delHallsList.push(this.halls[index])
            }
            this.halls.splice(index,1)
        }),
        delStand:action((areas,index)=>{
            areas.splice(index,1);
        }),
        addHis:action(()=>{
            let key;
            if(this.his.length==0){
                key=0;
            }else{
                key=this.his[this.his.length-1].key+1;
            }
            if(this.his.length>9){
                notificationWithIcon('error', `最多添加10个历史展览`)
                return;
            }
            this.his.push({
                key:key,
                name:'',
                url:'',
            })
        }),
        delHis:action((index)=>{
            this.his.splice(index,1)
        }),
        delActivity:action((index)=>{
            this.activity.splice(index,1)
        }),
        addActivity:action(()=>{
            let key;
            if(this.activity.length==0){
                key=0
            }else{
                key=this.activity[this.activity.length-1].key+1;
            }
            if(this.activity.length>19){
                notificationWithIcon('error', `最多添加20个展览活动`)
                return;
            }
            this.activity.push({
                key:key,
                name:'',
                url:'',
            })
        }),
        areaChange:action((key1,key2,e)=>{
            this.halls.map(hall=>{
                if(hall.key===key1){
                    let value=e.target.value;
                    let ind=0;
                    let tempArea='';
                    hall.areas.map((area,index)=>{
                        if(area.key===key2){
                            area.areaName=value;
                            ind=index;
                            tempArea=area;
                        }
                    });
                    let lessIndex=ind-1;
                    let moreIndex=ind+1;
                    let indexChange=false;
                    while(lessIndex>=0){
                        if(value==""||(hall.areas[lessIndex].areaName!=""&&hall.areas[lessIndex].areaName<=value)){
                            break;
                        }else{
                            hall.areas[ind]=hall.areas[lessIndex];
                            ind=lessIndex
                            indexChange=true;
                        }
                        --lessIndex;
                    }
                    while(!indexChange&&moreIndex<hall.areas.length){
                        if(value!=""&&(hall.areas[moreIndex].areaName==""||hall.areas[moreIndex].areaName>=value)){
                            break;
                        }else{
                            hall.areas[ind]=hall.areas[moreIndex];
                            ind=moreIndex
                        }
                        ++moreIndex;
                    }
                    hall.areas[ind]=tempArea;

                }
            });
        }),
        handleBaseInfo:action((form)=>{
            form.validateFieldsAndScroll((err,values)=> {
                if (!err) {
                    this.standTotal=values['standTotal']
                    let place={}
                    if(values['place']!=undefined&&values['place']!=null){
                        place.province=values['place'][0]
                        place.city=values['place'][1]
                        place.area=values['place'][2]
                    }
                    let url=''
                    if(values['officialUrl']!=undefined&&values['officialUrl']!=null&&values['officialUrl']!=''){
                        url=this.urlPre+values['officialUrl'];
                    }
                    let img=''
                    if(values['expoImg']!=undefined&&values['expoImg']!=null&&values['expoImg'].file!=undefined) {
                        img = values['expoImg'].file.response.result.key;
                    }
                    this.loading=true;
                    axios.post('/api/expo/create/baseInfo',{
                        'expoName':values['expoName'],
                        'startTime':values['time'][0].format('YYYY-MM-DD HH:mm:ss'),
                        'endTime':values['time'][1].format('YYYY-MM-DD HH:mm:ss'),
                        'standTotal':values['standTotal'],
                        'expoScope':values['expoScope'],
                        'expoResume':values['expoResume'],
                        'street':values['street'],
                        'location':values['location'],
                        'province':place.province,
                        'city':place.city,
                        'area':place.area,
                        'officialUrl':url,
                        'expoImg':img,
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                this.id=response.data.result.expoId;
                                this.current++;
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });
                    this.loading=false;
                }
            })
        }),
        handleStand:action((form)=>{
            form.validateFieldsAndScroll((err,values)=> {
                if(!err){
                    this.loading=true;
                    let total=0;
                    let hallDto=[];
                    let halls=values.halls;
                    for(let i in halls){
                        let hall={}
                        hall.hallName=halls[i].name
                        for(let r in hallDto){
                            if(hallDto[r].hallName==hall.hallName){
                                this.loading=false;
                                notificationWithIcon('error', `展馆名不能相同`)
                                return;
                            }
                        }
                        hall.area=[];
                        for(let j in halls[i].areas){
                            let a=halls[i].areas[j];
                            let stand={};
                            stand.word=a.word;
                            stand.start=a.start;
                            stand.end=a.end;
                            total+=(parseInt(a.end)-parseInt(a.start))+1;
                            let isRe=false;
                            for(let k in hall.area){
                                if(hall.area[k].areaName==a.area){
                                    for(let s in hall.area[k].stand){
                                        if( hall.area[k].stand[s].word==stand.word){
                                            this.loading=false;
                                            notificationWithIcon('error', `相同展区下区域编号不能相同`)
                                            return;
                                        }
                                    }
                                    isRe=true;
                                    hall.area[k].stand.push(stand);
                                    break;
                                }
                            }
                            if(!isRe){
                                let area={}
                                area.stand=[]
                                area.areaName=a.area;
                                area.stand.push(stand)
                                hall.area.push(area);
                            }
                        }
                        hallDto.push(hall);
                    }
                    if(total!=this.standTotal){
                        this.loading=false;
                        notificationWithIcon('error', `展位总数必须为${this.standTotal}`)
                        return;
                    }
                    axios.post('/api/expo/create/stand', {
                        hallDto:hallDto,
                        expoId:this.id,
                        standTotal:this.standTotal,
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                this.current++;
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });
                    this.loading=false;
                }
            });
        }),
        handleOther:action((form)=>{
            form.validateFieldsAndScroll((err,values)=> {
                if(!err){
                    let hasErr=false;
                    if(values.his!=undefined&&values.his.length>0){
                        let history=[]
                        this.loading=true;
                        for(let i in values.his){
                            let h={}
                            h.expoId=this.id;
                            h.hisExpoName=values.his[i].name
                            h.hisExpoUrl="http://chinaexpo365.com/"+values.his[i].url
                            history.push(h)
                        }
                        axios.post('/api/expo/create/expoHistory', {
                            expoHistory:history,
                            expoId:this.id,
                        })
                            .then((response) => {
                                if (response.data.status.code === 1) {

                                }
                                else {
                                    hasErr=true;
                                    notificationWithIcon('error', response.data.status.message, "")
                                }
                            })
                            .catch(function (error) {
                                console.log(error)
                                hasErr=true;
                                notificationWithIcon('error', '发生错误', error.response)
                            });
                    }
                    if(values.activity!=undefined&&values.activity.length>0) {
                        let activity=[];
                        for(let i in values.his){
                            let a={}
                            a.expoId=this.id;
                            a.activityName=values.activity[i].name
                            a.activityUrl="http://chinaexpo365.com/"+values.activity[i].url
                            activity.push(a)
                        }
                        axios.post('/api/expo/create/expoActivity', {
                            activityList: activity,
                            expoId: this.id,
                        })
                            .then((response) => {
                                if (response.data.status.code === 1) {

                                }
                                else {
                                    hasErr=true;
                                    notificationWithIcon('error', response.data.status.message, "")
                                }
                            })
                            .catch(function (error) {
                                console.log(error)
                                hasErr=true;
                                notificationWithIcon('error', '发生错误', error.response)
                            });
                    }
                    this.loading=false;
                    if(!hasErr){
                        this.current++;
                    }
                }
            })
        }),
        next:action(()=>{
            this.current++;
        }),
        prev:action(()=>{
            this.current--;
        }),
        getExhibition:action((status)=>{
            this.loading=true;
            let url=''
            if(status==1){
                url='/api/expo/getExpo?status=no'
            }else if(status==-1) {
                url = '/api/expo/getExpo?status=yes'
            }else{
                notificationWithIcon('error','参数错误')
                return
            }
            axios.get(url)
                .then((response)=> {
                    if(response.data.status.code===1) {
                        if(response.data.result.expo!=undefined) {
                            response.data.result.expo.map(ex=>{
                                let time='';
                                if(ex.startTime!=undefined&&ex.startTime!=null){
                                    time+=ex.startTime.substring(0,ex.startTime.length-3);
                                }
                                time+=' ~ ';
                                if(ex.endTime!=undefined&&ex.endTime!=null){
                                    time+=ex.endTime.substring(0,ex.endTime.length-3);
                                }
                                ex.time=time;
                            })
                            this.list = response.data.result.expo
                        }else{
                            this.list =[];
                        }

                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览列表失败",error.response)
                    console.log(error);
                });
            this.loading=false;
        }),
        delExpo:action((id)=>{
            axios.post('/api/expo/cancelExpo', {
                expoId: id,
            })
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.list.map((l,index)=>l.id==id&&this.list.splice(index,1));
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        getExhibitionDetail:action((id)=>{
            this.loading=true;
            axios.get('/api/expo/getExpoInfo?expoId='+id)
                .then((response)=> {
                    if(response.data.status.code===1) {
                        this.exhibitionInfo=response.data.result
                        let url=this.exhibitionInfo.officialUrl
                        if(url!=null&&url.length>7){
                            url=url.substring(url.indexOf('//')+2)
                            this.exhibitionInfo.officialUrl=url;
                        }
                        this.imageUrl=this.exhibitionInfo.expoImg
                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览失败",error.response)
                    console.log(error);
                });
            axios.get('/api/expo/getExpoStand?expoId='+id)
                .then((response)=> {
                    if(response.data.status.code===1) {
                        let stand=response.data.result;
                        let halls=[]
                        for(let i in stand){
                            let key=0;
                            let hall={};
                            hall.key=i;
                            hall.id=stand[i].id;
                            hall.name=stand[i].hallName;
                            hall.areas=[]
                            for(let j in stand[i].area){
                                let areas=stand[i].area[j];
                                for(let k in areas.stand){
                                    let area={};
                                    area.key=key++;
                                    area.areaName=areas.areaName;
                                    area.word=areas.stand[k].word;
                                    area.start=areas.stand[k].start;
                                    area.end=areas.stand[k].end;
                                    hall.areas.push(area);
                                }
                            }
                            hall.maxKey=key-1;
                            halls.push(hall);
                        }
                        this.halls=halls;
                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览失败",error.response)
                    console.log(error);
                });
            axios.get('/api/expo/getExpoHistory?expoId='+id)
                .then((response)=> {
                    if(response.data.status.code===1) {
                        let his=[]
                        response.data.result.hisExpo.map((h,index)=> {
                            let url = h.hisExpoUrl;
                            if (url.length > 24) {
                                url = url.substring(url.indexOf("chinaexpo365.com/") + 17);
                            }
                            his.push({
                                key: index,
                                name: h.hisExpoName,
                                url: url,
                            })
                        });
                        this.his=his;
                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览失败",error.response)
                    console.log(error);
                });
            axios.get('/api/expo/getExpoActivity?expoId='+id)
                .then((response)=> {
                    if(response.data.status.code===1) {
                        let act=[];
                        response.data.result.expoActivity.map((h,index)=>{
                            let url=h.activityUrl;
                            if(url.length>24){
                                url=url.substring(url.indexOf("chinaexpo365.com/")+17);
                            }
                            act.push({
                                key:index,
                                name:h.activityName,
                                url:url,
                            })
                        });
                        this.activity=act;
                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览失败",error.response)
                    console.log(error);
                });
            this.loading=false;
            this.hasProps=false
        }),
        clearExhibitionDetail:action(()=>{
            this.halls=[{
                key:0,
                name:'',
                maxKey:0,
                areas:[{
                    key:0,
                    areaName: '',
                    word:'',
                    start:'',
                    end:'',
                }]
            }]
            this.exhibitionInfo={}
            this.his=[]
            this.imageUrl=''
            this.activity=[]
            this.hasProps=true;
            this.delHallsList=[]
        }),
        updateInfo:action((id,form)=>{
            form.validateFieldsAndScroll((err,values)=> {
                if (!err) {
                    this.standTotal=values['standTotal']
                    let place={}
                    if(values['place']!=undefined&&values['place']!=null){
                        place.province=values['place'][0]
                        place.city=values['place'][1]
                        place.area=values['place'][2]
                    }
                    let url=''
                    if(values['officialUrl']!=undefined&&values['officialUrl']!=null&&values['officialUrl']!=''){
                        url=this.urlPre+values['officialUrl'];
                    }
                    let img=''
                    if(values['expoImg']!=undefined&&values['expoImg']!=null&&values['expoImg'].file!=undefined) {
                        img = values['expoImg'].file.response.result.key;
                    }else{
                        img=this.exhibitionInfo.key;
                    }
                    let hallDto=[];
                    let halls=values.halls;
                    let total=0;
                    for(let i in halls){
                        let hall={}
                        hall.hallName=halls[i].name
                        hall.id=halls[i].id;
                        for(let r in hallDto){
                            if(hallDto[r].hallName==hall.hallName){
                                notificationWithIcon('error', `展馆名不能相同`)
                                return;
                            }
                        }
                        hall.area=[];
                        for(let j in halls[i].areas){
                            let a=halls[i].areas[j];
                            let stand={};
                            stand.word=a.word;
                            stand.start=a.start;
                            stand.end=a.end;
                            total+=(parseInt(a.end)-parseInt(a.start)+1);
                            let isRe=false;
                            for(let k in hall.area){
                                if(hall.area[k].areaName==a.area){
                                    for(let s in hall.area[k].stand){
                                        if( hall.area[k].stand[s].word==stand.word){
                                            notificationWithIcon('error', `相同展区下区域编号不能相同`)
                                            return;
                                        }
                                    }
                                    isRe=true;
                                    hall.area[k].stand.push(stand);
                                    break;
                                }
                            }
                            if(!isRe){
                                let area={}
                                area.stand=[]
                                area.areaName=a.area;
                                area.stand.push(stand)
                                hall.area.push(area);
                            }
                        }
                        hallDto.push(hall);
                    }
                    if(total!=this.standTotal){
                        notificationWithIcon('error', `展位总数必须与所填展位数相等`)
                        return;
                    }
                    this.loading=true;
                    axios.post('/api/expo/modifyExpo', {
                        'id':id,
                        'expoName':values['expoName'],
                        'startTime':values['time'][0].format('YYYY-MM-DD HH:mm:ss'),
                        'endTime':values['time'][1].format('YYYY-MM-DD HH:mm:ss'),
                        'standTotal':values['standTotal'],
                        'expoScope':values['expoScope'],
                        'expoResume':values['expoResume'],
                        'street':values['street'],
                        'location':values['location'],
                        'province':place.province,
                        'city':place.city,
                        'area':place.area,
                        'officialUrl':url,
                        'expoImg':img,
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                let hasErr=false;
                                this.delHallsList.map(hall=>{
                                    let hallId=hall.id;
                                    axios.post('/api/expo/delHall', {
                                        hallId:hallId,
                                        expoId:id,
                                    })
                                        .then((response) => {
                                            if (response.data.status.code === 1) {
                                            }
                                            else {
                                                hasErr=true;
                                                notificationWithIcon('error', response.data.status.message, "")
                                            }
                                        })
                                        .catch(function (error) {
                                            console.log(error)
                                            hasErr=true;
                                            notificationWithIcon('error', '发生错误', error.response)
                                        });
                                })
                                axios.post('/api/expo/create/stand', {
                                    hallDto:hallDto,
                                    expoId:id,
                                    standTotal:this.standTotal,
                                })
                                    .then((response) => {
                                        if (response.data.status.code === 1) {
                                        }
                                        else {
                                            hasErr=true;
                                            notificationWithIcon('error', response.data.status.message, "")
                                        }
                                    })
                                    .catch(function (error) {
                                        console.log(error)
                                        hasErr=true;
                                        notificationWithIcon('error', '发生错误', error.response)
                                    });
                                if(values.his!=undefined&&values.his.length>0){
                                    let history=[]
                                    for(let i in values.his){
                                        let h={}
                                        h.expoId=id;
                                        h.hisExpoName=values.his[i].name
                                        h.hisExpoUrl="http://chinaexpo365.com/"+values.his[i].url
                                        history.push(h)
                                    }
                                    axios.post('/api/expo/modifyHisExpo', {
                                        expoHistory:history,
                                        expoId:id,
                                    })
                                        .then((response) => {
                                            if (response.data.status.code === 1) {
                                            }
                                            else {
                                                hasErr=true;
                                                notificationWithIcon('error', response.data.status.message, "")
                                            }
                                        })
                                        .catch(function (error) {
                                            console.log(error)
                                            hasErr=true;
                                            notificationWithIcon('error', '发生错误', error.response)
                                        });
                                }
                                if(values.activity!=undefined&&values.activity.length>0) {
                                    let activity = [];
                                    for (let i in values.his) {
                                        let a = {}
                                        a.expoId = id;
                                        a.activityName = values.activity[i].name
                                        a.activityUrl = "http://chinaexpo365.com/" + values.activity[i].url
                                        activity.push(a)
                                    }
                                    axios.post('/api/expo/modifyExpoActivity', {
                                        activityList: activity,
                                        expoId: id,
                                    })
                                        .then((response) => {
                                            if (response.data.status.code === 1) {

                                            }
                                            else {
                                                hasErr=true;
                                                notificationWithIcon('error', response.data.status.message, "")
                                            }
                                        })
                                        .catch(function (error) {
                                            console.log(error)
                                            hasErr=true;
                                            notificationWithIcon('error', '发生错误', error.response)
                                        });
                                }
                                this.loading=false;
                                if(!hasErr){
                                    Modal.confirm({
                                        title: '修改成功',
                                        content:'成功修改展览信息，是否前去看看展览',
                                        iconType:'check-circle',
                                        okText:'立即前去',
                                        cancelText:'取消',
                                        onOk:()=>window.open(`/exhibition/detail?id=${id}`, '_blank').location,
                                    });
                                }
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }

                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });

                }
            });
        }),
        resetCurrent:action(()=>{
            this.actions.clearExhibitionDetail();
            this.current=0;
        }),
    }

}

export default new ExhibitionStore()

